import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { Route } from '@/models/connect';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {

  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = <T extends Route>(
  router: T[] = [],
  pathname: string,
): T | undefined => {
  const authority = router.find(
    ({ routes, path = '/', target = '_self' }) =>
      (path && target !== '_blank' && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};

export const getRouteAuthority = (path: string, routeData: Route[]) => {
  let authorities: string[] | string | undefined;
  routeData.forEach((route) => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

/**
 * 递归执行替代setInterval执行定时任务
 * @param func 要驱动的函数
 * @param time 方法执行时间
 * @param interval 方法执行间隔
 * @param isFirst 是否是初次执行
 * @param stopCallback 递归收敛条件,返回方法停止标志
 * @param stopRunCallback 前置停止条件
 */
export const trigger =(func:any, time:Date, interval:Number, isFirst:boolean,stopCallback:boolean,stopRunCallback:boolean,extra:any) =>{
  if (stopRunCallback && stopRunCallback(extra)) return;

  if (isFirst) {
    func(isFirst)
  } else {
    const current = new Date().valueOf();
    const n = current - time;
    if (n > interval) {
      func(isFirst);
      time = current
    }
  }
  if (!stopCallback()) {
    setTimeout(()=>
        requestAnimationFrame(() => trigger(func, time, interval, false, stopCallback,stopRunCallback,extra))
      ,0)
  }
};

String.format = function()
{
  if( arguments.length == 0 )
  {
    return null;
  }
  var str = arguments[0];
  for(var i=1;i<arguments.length;i++)
  {
    var re = new RegExp('\\{' + (i-1) + '\\}','gm');
    str = str.replace(re, arguments[i]);
  }
  return str;
}
